package com.wjb.xietong.W3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.wjb.xietong.component.AppGlobal;
import com.wjb.xietong.util.LogD;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageTools {

	public static void saveBitmapImage(String path, String fileName,
			String fileType, Bitmap mBitmap) {
		if (null != path) {
			File filePath = new File(path.substring(0, path.lastIndexOf("/")));
			if (!filePath.exists()) {
				filePath.mkdirs();
			}
			
			if(null != fileName && !"".equals(fileName)){
				File fileDire = new File(path);
				if(!fileDire.exists()){
					fileDire.mkdirs();
				}
			}
			
			if (null == fileName) {
				fileName = "";
			}
			if (null == fileType) {
				fileType = "";
			}

			File f = new File(path + fileName + fileType);
			try {
				f.createNewFile();
			} catch (IOException e) {
				LogD.output("Exception:" + e.getMessage());
			}

			FileOutputStream fOut = null;
			try {
				fOut = new FileOutputStream(f);
			} catch (FileNotFoundException e) {
				LogD.output("Exception:" + e.getMessage());
			}
			
			if(null == fOut){
				LogD.output("Exception: FileOutputStream is null!");
				return;
			}
			
			if(null == mBitmap){
				LogD.output("Exception: mBitmap is null!");
				return;
			}
			mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
			try {
				fOut.flush();
			} catch (IOException e) {
				LogD.output("Exception:" + e.getMessage());
			}
			try {
				fOut.close();
			} catch (IOException e) {
				LogD.output("Exception:" + e.getMessage());
			}
		}
	}
	
	public static boolean fileExits(final String filePath){
		if(null != filePath){
			File file = new File(filePath);
			return file.exists();
		}
		return false;
	} 
	
	public static boolean fileExist(String userId, String iconId){
		final String filePath = AppGlobal.getInstance().getAppPath() + "/" + userId + iconId;
		return fileExits(filePath);
	}
	
	public static Bitmap getBitMap(String userId, String iconId){
		final String filePath = AppGlobal.getInstance().getAppPath() + "/" + userId + iconId;
		return getBitMap(filePath);
	}
	
	public static Bitmap getBitMap(final String filePath){
		File file = null;
		if(null != filePath){
			file = new File(filePath);
			if(!file.exists()){
				LogD.output("File Not Exits:" + filePath);
				return null;
			}
		}
		
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			LogD.output("Exception:" + e.getMessage());
		}
		if(null != fis){
			return BitmapFactory.decodeStream(fis);
		}
		
		return null;
	}
}
